<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Controller;
use App\Libs\wrapper\VirtualPost;
use Illuminate\Support\Facades\DB;

class VirtualPostController extends Controller
{
    public function index()
    {
        $request = request()->all();
        list($count, $result, $total, $is_admin) = VirtualPost::getIndex($request);
        $user_list = Db::table('vp_matter_list as vml')->select(['u.id', 'u.account'])->join('users as u', 'vml.uid', '=', 'u.id')->groupBy('uid')->get();
        $this->back('获取成功', '200', ['list' => $result, 'count' => $count, 'total' => $total, 'is_admin' => $is_admin, 'user_list' => $user_list]);
    }

    /**
     * 设置事项(定时任务,每月月初执行)
     */
    public function setMatterList()
    {
        $deal_time = strtotime(request()->post('month'));
        $checkRes = Db::table('vp_matter_list')->where(['ym' => date('Ym', $deal_time)])->first();
        if ($checkRes) {
            echo "已生成过事项，请勿重复生成";
            exit();
        }
        $res = DB::table('vp_matter as vm')
            ->select(['vm.matter_name', 'vm.type', 'vm.date', 'vp.ids', 'vp.id as post_id', 'vm.id as matter_id', 'vm.is_auto'])
            ->leftJoin('vp_post as vp', 'vp.id', '=', 'vm.post_id')
            ->where(['vp.is_del' => 0, 'vm.is_del' => 0])
            ->where('vm.id', '>', 0)
            ->get()
            ->toArrayList();
        try {
            VirtualPost::getDateRes($res);
            echo '新增成功';
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * 定时任务-自动获取当日需要自动获取的所有数据报表
     */
    public function checkAutoList()
    {
        VirtualPost::checkAutoMatter();
    }

    /**
     * 将数据转成Excel要用的格式
     */
    public function setMatterExcel()
    {
        $is_export = request()->get('is_export', 0);
        $list_id = request()->get('list_id', '');
        $list = DB::table('vp_matter_detail as vmd')->leftJoin('vp_matter_list as vml', 'vml.id', '=', 'vmd.list_id')->select(['vmd.*', 'vml.matter_name', 'vml.deal_date'])->where(['list_id' => $list_id])
            ->first();
        if (!$list) return $this->back('暂无数据');
        if ($is_export) {
            VirtualPost::setMatterExcel(json_decode($list->snapshot, true), $list->matter_name,$list->deal_date);
        }
        return $this->back('获取成功', '200', ['list' => json_decode($list->snapshot, true), 'member_list' => VirtualPost::personLiable($list->matter_name)]);
    }

    /**
     * 获取事项快照
     */
    public function getMatterSnapshot()
    {
        $is_export = request()->get('is_export', 0);
        $list_id = request()->get('list_id', '');
        $list = Db::table('vp_matter_detail')->where(['list_id' => $list_id])->first()->toArray();
        return $this->back('获取成功', '200', $list);
    }


    /**
     * 获取搜索列表
     */
    public function getSearchList()
    {
        $request = request()->all();
        $list = VirtualPost::getSearchList();
        $this->back('获取成功', '200', $list);
    }

    /**
     * 上传文件
     */
    public function uploadFile()
    {
        $id = request()->post('id');
        $filePath = request()->post('file');
        $desc = request()->post('desc');
        $user = VirtualPost::getUser();
        $deal_date = Db::table('vp_matter_list')->where(['id' => $id])->first()->deal_date;
        if (!$deal_date) $this->back('该事项不存在');
        $status = 2;
        if (strtotime($deal_date) > time()) {
            $status = 1;
        }
        $res = DB::table('vp_matter_detail')
            ->updateOrInsert(['list_id' => $id], ['list_id' => $id, 'desc' => $desc ?: '', 'update_user' => $user->Id, 'file' => $filePath, 'status' => $status, 'update_time' => time(), 'update_date' => date('Y-m-d', time())]);

        if ($res) {
            $this->back('上传成功', '200');
        }
        $this->back('网络繁忙，请重新提交');
    }

    /**
     * 上传图片
     */
    public function uploadImg()
    {
        $id = request()->post('id');
        $img = request()->post('img');
        $res = DB::table('vp_matter_detail')
            ->updateOrInsert(['list_id' => $id], ['list_id' => $id, 'img' => $img]);
        if ($res) {
            $this->back('上传成功', '200');
        }
        $this->back('网络繁忙，请重新提交');
    }

    /**
     * 评价
     */
    public function comment()
    {
        $id = request()->post('id');
        $comment = request()->post('comment', '');
        $score = request()->post('score');
        $user = VirtualPost::getUser();
        $res = DB::table('vp_matter_detail')
            ->updateOrInsert(['list_id' => $id], ['list_id' => $id, 'comments' => $comment, 'comment_user' => $user->Id, 'score' => $score, 'comment_time' => time(), 'comment_date' => date('Y-m-d', time())]);
        if ($res) {
            $this->back('更新成功', '200');
        }
        $this->back('更新失败');
    }

    /**
     * 事项列表
     */
    public function matterList()
    {
        $res = DB::table('vp_matter as vm')->where(['is_del' => 0])->get();
        $this->back('更新成功', '200', ['list' => $res ?: []]);
    }

    /**
     * 岗位列表
     */
    public function postList()
    {
        $res = VirtualPost::postList();
        $this->back('获取成功', '200', ['list' => $res ?: []]);
    }

    /**
     * 获取我的岗位
     */
    public function myPost()
    {
        $uid = VirtualPost::getUser()->Id;
        $res = DB::table('vp_post')
            ->select(['id', 'name'])
            ->where(['is_del' => 0])
//            ->whereRaw("find_in_set({$uid},`ids`)")
            ->get();
        $this->back('获取成功', '200', ['list' => $res ?: []]);
    }

    /**
     * 创建事项（临时）
     */
    public function createMatter()
    {
        $res = VirtualPost::createMatter();

        return $this->back($res['msg'] ?? '未知错误', $res['code'] ?? 500, $res['data'] ?? []);
    }

    /**
     * 执行结果
     */
    public function createResults()
    {
        $id = request()->post('id');
        $results = request()->post('results');
        $res = DB::table('vp_matter_detail')
            ->updateOrInsert(['list_id' => $id], ['list_id' => $id, 'results' => $results]);
        if ($res) {
            $this->back('更新成功', '200');
        }
        $this->back('更新失败');
    }

    public function getMatterByPost()
    {
        $id = request()->post('post_id');
        $res = DB::table('vp_matter')->select(['id', 'matter_name', 'type', 'date'])
            ->where(['post_id' => $id, 'is_del' => 0])->get();
        $this->back('获取成功', '200', ['list' => $res]);

    }

    /**
     * 新增岗位
     */
    public function createPost()
    {
        try {
            $res = VirtualPost::insertPost();
            if ($res) $this->back('新增成功', '200');
            $this->back('新增失败');
        } catch (\Exception $e) {
            $this->back($e->getMessage());
        }
    }

    /**
     * 编辑岗位
     */
    public function updatePost()
    {
        try {
            $res = VirtualPost::updatePost();
            if ($res) $this->back('更新成功', '200');
            $this->back('更新失败');
        } catch (\Exception $e) {
            $this->back($e->getMessage());
        }
    }

    /**
     * 删除岗位
     */
    public function delPost()
    {
        try {
            $res = VirtualPost::delPost();
            if ($res) $this->back('删除成功', '200');
            $this->back('删除失败');
        } catch (\Exception $e) {
            $this->back($e->getMessage());
        }
    }

    /**
     * 设置事项
     */
    public function setMatter()
    {
        $res = VirtualPost::setMatter();
        if ($res) $this->back('保存成功', '200');
        $this->back('保存失败');
    }

//    /**
//     * 岗位绑定事项
//     */
//    public function bindMatter()
//    {
//        $matterIds = request()->post('matterIds', '');
//        $post_id = request()->post('post_id', '');
//        if (!$matterIds) $this->back('matterIds不能为空');
//        if (!$post_id) $this->back('post_id不能为空');
//        try {
//            $res = VirtualPost::bindMatter($matterIds, $post_id);
//            if ($res) $this->back('绑定成功', '200');
//        } catch (\Exception $e) {
//            $this->back($e->getMessage());
//        }
//    }

    /**
     * 删除事项
     */
    public function delMatter()
    {
        $id = request()->post('matter_id');
        if (!$id) $this->back('matter_id不存在');
        $res = DB::table('vp_matter')->where(['id' => $id])->update(['is_del' => 1, 'update_time' => time(), 'update_user' => VirtualPost::getUser()->Id]);
        if ($res) $this->back('删除成功', '200');
        $this->back('删除失败');
    }


}